<template>
    <j-modal
            :width="modalWidth"
            :visible="visible"
            :title="title"
            switchFullscreen
            @ok="handleSubmit"
            @cancel="close"
            style="top:50px"
            cancelText="关闭"
    >
        <a-tabs :active-key="activeKey" @tabClick="tabClick">
<!--                        <a-tab-pane key="org" tab="组织">-->

<!--                            <a-spin tip="Loading..." :spinning="typeLoading">-->
<!--                                <a-row :gutter="10" style="background-color: #ececec; padding: 10px; margin: -10px" v-if="visible">-->
<!--                                    <a-col :md="6" :sm="24">-->
<!--                                        <a-card :bordered="false">-->
<!--                                            &lt;!&ndash;组织机构&ndash;&gt;-->
<!--                                            <a-tree-->
<!--                                                    :checkStrictly="false"-->
<!--                                                    v-model="selectedKeys"-->
<!--                                                    :checkable="true"-->
<!--                                                    @check="handleCheckbox"-->
<!--                                                    @select="handleCheckbox"-->
<!--                                                    :multiple="true"-->
<!--                                                    :selectedKeys="selectedKeys"-->
<!--                                                    :expandedKeys.sync="expandedKeys"-->
<!--                                                    :auto-expand-parent="true"-->
<!--                                                    :dropdownStyle="{maxHeight:'200px',overflow:'auto'}"-->
<!--                                                    :replaceFields="{children: 'children', title: 'name', key: 'code'}"-->
<!--                                                    :treeData="treeData"-->
<!--                                            />-->
<!--                                        </a-card>-->
<!--                                    </a-col>-->
<!--                                    <a-col :md="18" :sm="24">-->
<!--                                        <a-card :bordered="false">-->
<!--                                            <a-table-->
<!--                                                    ref="table"-->
<!--                                                    :scroll="scrollTrigger"-->
<!--                                                    size="middle"-->
<!--                                                    rowKey="code"-->
<!--                                                    :columns="categoryColumns"-->
<!--                                                    :dataSource="categoryData"-->
<!--                                                    :pagination="false"-->

<!--                                            >-->
<!--                                                &lt;!&ndash;                                    :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange,type: getType}"&ndash;&gt;-->
<!--                                            </a-table>-->
<!--                                        </a-card>-->
<!--                                    </a-col>-->
<!--                                </a-row>-->
<!--                            </a-spin>-->
<!--                        </a-tab-pane>-->
<!--            <a-tab-pane key="position" tab="职位">-->
<!--                <a-spin tip="Loading..." :spinning="false">-->
<!--                    <a-row :gutter="10" style="background-color: #ececec; padding: 10px; margin: -10px" v-if="visible">-->
<!--                        <a-col :md="12" :sm="24">-->
<!--                            <a-card :bordered="false">-->
<!--                                <a-form layout="inline" @keyup.enter.native="searchQuery">-->
<!--                                    <a-row :gutter="24">-->
<!--                                        <a-col :xl="10" :lg="9" :md="8" :sm="24">-->
<!--                                            <a-form-item label="职位编号">-->
<!--                                                <a-input placeholder="请输入名称模糊查询" v-model="queryParam.positionCode"></a-input>-->
<!--                                            </a-form-item>-->
<!--                                        </a-col>-->
<!--                                        <a-col :xl="10" :lg="9" :md="8" :sm="24">-->
<!--                                            <a-form-item label="职位名称">-->
<!--                                                <a-input placeholder="请输入名称模糊查询" v-model="queryParam.positionName"></a-input>-->
<!--                                            </a-form-item>-->
<!--                                        </a-col>-->

<!--                                        <div style="float: left;overflow: hidden;" class="table-page-search-submitButtons">-->
<!--                                            <a-col :xl="4" :lg="6" :md="8" :sm="24">-->
<!--                                                <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>-->
<!--                                            </a-col>-->
<!--                                        </div>-->
<!--                                    </a-row>-->
<!--                                </a-form>-->
<!--                                <a-table-->
<!--                                        ref="table"-->
<!--                                        size="middle"-->
<!--                                        bordered-->
<!--                                        :scroll="{-->
<!--          x:'max-content'-->
<!--        }"-->
<!--                                        tableLayout="auto"-->
<!--                                        rowKey="positionCode"-->
<!--                                        :columns="positionsColumns"-->
<!--                                        :dataSource="positions"-->
<!--                                        :pagination="ipagination"-->
<!--                                        :loading="loading"-->
<!--                                        :rowSelection="{selectedRowKeys: positionSelectedRowKeys,-->
<!--                                        onSelect: onSelect,onSelectAll:onSelectAll}"-->
<!--                                        @change="handleTableChange"-->
<!--                                >-->

<!--                                    <template slot="mainPosition" slot-scope="text, record, index" v-if="false">-->
<!--                                        {{text}}-->
<!--                                    </template>-->
<!--                                    <template slot="imgUrl" slot-scope="text, record, index">-->
<!--                                        <div class="anty-img-wrap">-->
<!--                                            <a-avatar shape="square" :src="record.imgUrl" icon="user"/>-->
<!--                                        </div>-->
<!--                                    </template>-->

<!--                                    <template slot="status" slot-scope="text">{{ text | isActiveStatus }}</template>-->
<!--                                </a-table>-->

<!--                            </a-card>-->
<!--                        </a-col>-->
<!--                        <a-col :md="12" :sm="24">-->
<!--                            <a-card :bordered="false">-->
<!--                                <a-table-->
<!--                                        ref="table"-->
<!--                                        size="middle"-->
<!--                                        bordered-->
<!--                                        :scroll="{-->
<!--          x:'max-content'-->
<!--        }"-->
<!--                                        tableLayout="auto"-->
<!--                                        rowKey="positionCode"-->
<!--                                        :columns="positionsDataColumns"-->
<!--                                        :dataSource="positionsData"-->
<!--                                >-->

<!--                                    <template slot="mainPosition" slot-scope="text, record, index">-->
<!--                                        <a-radio-group v-model="record.mainPosition" @change="onPositionChange(record,this)">-->
<!--                                            <a-radio :value="0">-->
<!--                                                主职-->
<!--                                            </a-radio>-->
<!--                                            <a-radio :value="1">-->
<!--                                                副职-->
<!--                                            </a-radio>-->
<!--                                        </a-radio-group>-->
<!--                                    </template>-->
<!--                                    <template slot="imgUrl" slot-scope="text, record, index">-->
<!--                                        <div class="anty-img-wrap">-->
<!--                                            <a-avatar shape="square" :src="record.imgUrl" icon="user"/>-->
<!--                                        </div>-->
<!--                                    </template>-->

<!--                                    <template slot="status" slot-scope="text">{{ text | isActiveStatus }}</template>-->

<!--                                    <template slot="action" slot-scope="text, record, index">-->
<!--                                        <a @click="handleDelete(record)">删除</a>-->
<!--                                    </template>-->
<!--                                </a-table>-->
<!--                            </a-card>-->
<!--                        </a-col>-->
<!--                    </a-row>-->
<!--                </a-spin>-->
<!--            </a-tab-pane>-->
          <a-tab-pane key="user" tab="用户">
            <a-spin tip="Loading..." :spinning="false">
              <a-row :gutter="10" style="background-color: #ececec; padding: 10px; margin: -10px" v-if="visible">
                <a-col :md="12" :sm="24">
                  <a-card :bordered="false">
                    <a-form layout="inline" @keyup.enter.native="searchQuery">
                      <a-row :gutter="24">
                        <a-col :xl="10" :lg="9" :md="8" :sm="24">
                          <a-form-item label="用户账号">
                            <a-input placeholder="请输入名称模糊查询" v-model="queryParam.realName"></a-input>
                          </a-form-item>
                        </a-col>
                        <a-col :xl="10" :lg="9" :md="8" :sm="24">
                          <a-form-item label="用户名称">
                            <a-input placeholder="请输入名称模糊查询" v-model="queryParam.userName"></a-input>
                          </a-form-item>
                        </a-col>

                        <div style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                          <a-col :xl="4" :lg="6" :md="8" :sm="24">
                            <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                          </a-col>
                        </div>
                      </a-row>
                    </a-form>
                    <a-table
                      ref="table"
                      class='Table'
                      size="middle"
                      bordered
                      :scroll="{
          x:'max-content'
        }"
                      tableLayout="auto"
                      rowKey="id"
                      :columns="usersColumns"
                      :dataSource="users"
                      :pagination="ipagination"
                      :loading="loading"
                      :rowSelection="{selectedRowKeys: userSelectedRowKeys, onSelect: onSelect,onSelectAll:onSelectAll}"
                      @change="handleTableChange"
                    >
                      <template slot="imgUrl" slot-scope="text, record, index">
                        <div class="anty-img-wrap">
                          <a-avatar shape="square" :src="record.imgUrl" icon="user"/>
                        </div>
                      </template>

                      <template slot="status" slot-scope="text">{{ text | isActiveStatus }}</template>
                    </a-table>

                  </a-card>
                </a-col>
                <a-col :md="12" :sm="24">
                  <a-card :bordered="false">
                    <a-table
                      ref="table"
                      size="middle"
                      class='Table'
                      bordered
                      :scroll="{
          x:'max-content'
        }"
                      tableLayout="auto"
                      rowKey="id"
                      :columns="usersColumns"
                      :dataSource="usersData"
                    >
                      <template slot="imgUrl" slot-scope="text, record, index">
                        <div class="anty-img-wrap">
                          <a-avatar shape="square" :src="record.imgUrl" icon="user"/>
                        </div>
                      </template>

                      <template slot="status" slot-scope="text">{{ text | isActiveStatus }}</template>

                      <template slot="action" slot-scope="text, record, index">
                        <a @click="handleDelete(record)">删除</a>
                      </template>
                    </a-table>
                  </a-card>
                </a-col>
              </a-row>
            </a-spin>
          </a-tab-pane>
        </a-tabs>

    </j-modal>
</template>

<script>
    import {filterObj} from '@/utils/util'
    import {queryDepartTreeList, getUserList, queryUserByDepId} from '@/api/api'
    import {getAction, postAction} from "@/api/manage";
    import JInput from '@/components/cn-form/JInput.vue';
    import {getStore} from "@/utils/storage";
    import {PageListMixin} from '@/mixins/PageListMixin'

    export default {
        name: 'orgtoUser',
        components: {JInput},
        props: {
            modalWidth: {
                default() {
                    return '90%'
                }
            },
            'multi': Boolean
        },
        data() {
            return {
              description:'组织-用户配置组件',
                typeLoading: false,
                queryParam: {
                    code: "",
                    name: "",
                },
                treeData: [],
                categoryData: [],
                categoryColumns: [
                    {
                        title: '组织编号',
                        align: 'center',
                        dataIndex: 'code'
                    },
                    {
                        title: '组织名称',
                        align: 'center',
                        dataIndex: 'name'
                    }
                ],
                products: [],
                productData: [],
                productColumns: [
                    {
                        title: '#',
                        key: 'rowIndex',
                        width: 60,
                        align: 'center',
                        customRender: function (t, r, index) {
                            return parseInt(index) + 1
                        },
                    },
                    {
                        title: '商品图片',
                        align: 'center',
                        dataIndex: 'imgUrl',
                        width: 80,
                        ellipsis: true,
                        scopedSlots: {customRender: 'imgUrl'},
                    },
                    {
                        title: '商品编号',
                        align: 'center',
                        width: 120,
                        ellipsis: true,
                        dataIndex: 'code',
                    },
                    {
                        title: '商品名称',
                        align: 'center',
                        width: 120,
                        ellipsis: true,
                        dataIndex: 'name',
                    },
                    {
                        title: '状态',
                        align: 'center',
                        dataIndex: 'status',
                        width: 80,
                        ellipsis: true,
                        scopedSlots: {customRender: 'status'},
                    },
                    {
                        title: '操作',
                        align: 'center',
                        dataIndex: 'action',
                        width: 80,
                        ellipsis: true,
                        scopedSlots: {customRender: 'action'},
                    },
                ],
                positions: [],
                positionsData: [],
                positionsColumns: [
                    {
                        title: '#',
                        key: 'rowIndex',
                        width: 60,
                        align: 'center',
                        customRender: function (t, r, index) {
                            return parseInt(index) + 1
                        },
                    },
                    {
                        title: '职位编号',
                        align: 'center',
                        dataIndex: 'positionCode'
                    },
                    {
                        title: '职位名称',
                        align: 'center',
                        dataIndex: 'positionName'
                    },
                    {
                        title: '职位级别',
                        align: 'center',
                        dataIndex: 'positionLevel'
                    },
                    {
                        title: '操作',
                        align: 'center',
                        dataIndex: 'action',
                        width: 80,
                        ellipsis: true,
                        scopedSlots: {customRender: 'action'},
                    },
                ],
                positionsDataColumns: [
                    {
                        title: '#',
                        key: 'rowIndex',
                        width: 60,
                        align: 'center',
                        customRender: function (t, r, index) {
                            return parseInt(index) + 1
                        },
                    },
                    {
                        title: '职位编号',
                        align: 'center',
                        dataIndex: 'positionCode'
                    },
                    {
                        title: '职位名称',
                        align: 'center',
                        dataIndex: 'positionName'
                    },
                    {
                        title: '职位级别',
                        align: 'center',
                        dataIndex: 'positionLevel'
                    },
                    {
                        title: '职位类型',
                        align: 'center',
                        dataIndex: 'mainPosition',
                        scopedSlots: {customRender: 'mainPosition'},
                    },
                    {
                        title: '操作',
                        align: 'center',
                        dataIndex: 'action',
                        width: 80,
                        ellipsis: true,
                        scopedSlots: {customRender: 'action'},
                    },
                ],
              users: [],
              usersData: [],
              usersColumns: [
                    {
                        title: '#',
                        key: 'rowIndex',
                        width: 60,
                        align: 'center',
                        customRender: function (t, r, index) {
                            return parseInt(index) + 1
                        },
                    },
                    {
                        title: '用户账号',
                        align: 'center',
                        dataIndex: 'userName'
                    },
                    {
                        title: '用户名称',
                        align: 'center',
                        dataIndex: 'realName'
                    },
                    {
                        title: '操作',
                        align: 'center',
                        dataIndex: 'action',
                        width: 80,
                        ellipsis: true,
                        scopedSlots: {customRender: 'action'},
                    },
                ],
                scrollTrigger: {},
              userSelectedRowKeys: [],
                positionSelectedRowKeys: [],
              userSelectionRows: [],
                positionSelectionRows: [],
                title: '用户配置',
                selectedKeys: [],
                visible: false,
                form: this.$form.createForm(this),
                loading: false,
                expandedKeys: [],
                userInfo: this.$store.getters.userInfo,
                activeKey: 'user',
                url: {
                    list:  '/cnProductController/getProductListByCust',
                    selected:  '/cnTerminalController/getCnTerminalByIdOrTerminalCode'
                },
                record: null,

            }
        },
        mixins: [PageListMixin],
        computed: {
            // 计算属性的 getter
            getType: function () {
                return this.multi == true ? 'checkbox' : 'radio';
            }
        },
        watch: {
            visible(v) {
                if (v) {
                    this.getSelectdData().then(() => {
                        if (this.activeKey == 'org') {
                            this.queryDepartTree();
                        } else {
                            this.loadData()
                        }
                    })
                }
            },
            // activeKey() {
            //     if (this.activeKey == 'org') {
            //         this.queryDepartTree();
            //     } else {
            //         this.loadData()
            //     }
            // },
        },
        created() {
            // 该方法触发屏幕自适应
            this.resetScreenSize();
        },
        methods: {
            /**
             * 删除已选中商品
             * @param record
             */
            handleDelete(record) {
              if(this.activeKey == 'user'){
                this[this.activeKey + 'sData'].removeByCode(record, 'id')
                this[this.activeKey + 'SelectionRows'].removeByCode(record, 'id')
                this[this.activeKey + 'SelectedRowKeys'].remove(record['id'])
              }else{
                this[this.activeKey + 'sData'].removeByCode(record, this.activeKey + 'Code')
                this[this.activeKey + 'SelectionRows'].removeByCode(record, this.activeKey + 'Code')
                this[this.activeKey + 'SelectedRowKeys'].remove(record[this.activeKey + 'Code'])
              }
            },
            /**
             * 标签页的选中事件
             * @param name
             */
            tabClick(name) {
                this.activeKey = name
            },
            /**
             * 递归树结构数据，取出所有子元素
             * @param children
             * @param selected
             * @returns {*}
             */
            getAllChildren(children, selected) {
                if (children && children.length) {
                    children.map(child => {
                        selected.push(child)
                        this.getAllChildren(child.children, selected)
                    })
                }
                return selected
            },
            /**
             * 选中树节点操作
             * @param checkedKeys
             * @param checked 不等于undefined 表示当前事件为checkbox事件，否则为点击树节点事件
             * @param checkedNodes
             * @param node
             * @param event
             */
            handleCheckbox(checkedKeys, {checked, checkedNodes, node, event}) {
                if (checked !== undefined) {
                    //todo 当事件为checkbox事件时，checkedKeys当前选中的数据包含自节点数据
                    this.selectedKeys = checkedKeys
                    this.categoryData = this.getAllChildren(this.treeData, []).filter(node => checkedKeys.includes(node.code)).map(node =>
                        Object.assign({}, node, {
                            children: null
                        }))
                } else {
                    //todo 当事件为nodeClick事件时，checkedKeys当前选中数据为当前点击节点
                    const checkNodes = [node.dataRef, ...this.getAllChildren(node.dataRef.children, [])]
                    //todo 如果当前点击节点已经被选中，则执行删除操作
                    if (this.selectedKeys.includes(node.dataRef.code)) {
                        checkNodes.map(node => {
                            this.selectedKeys.remove(node.code)
                            //todo 从右边table删除选中数据
                            this.categoryData.remove(node)
                        })
                    } else {
                        this.selectedKeys = Array.from(new Set(this.selectedKeys.concat(checkNodes.map(node => node.code))));
                        //todo 添加选中数据到右边table
                        this.categoryData = Array.from(new Set([...this.categoryData, ...checkNodes.map(node => Object.assign({}, node, {
                            children: null
                        }))]));
                    }

                }
            },
            // 触发屏幕自适应
            resetScreenSize() {
                let screenWidth = document.body.clientWidth;
                if (screenWidth < 500) {
                    this.scrollTrigger = {x: 800};
                } else {
                    this.scrollTrigger = {};
                }
            },
            showModal(record) {
                this.userInfo = record
                this.visible = true;
                this.form.resetFields();
            },
            /**
             * 获取查询参数
             * @returns {*}
             */
            getQueryParams() {
                let param = Object.assign({}, this.queryParam);
                param.current = this.ipagination.current;
                param.size = this.ipagination.pageSize;
                return filterObj(param);
            },
            searchReset(num) {
                let that = this;
                if (num !== 0) {
                    that.loadData(1);
                }
                that[this.activeKey + 'SelectedRowKeys'] = [];
                that[this.activeKey + 'SelectionRows'] = [];
                that.selectedKeys = [];
                that[this.activeKey + 'sData'] = []
                that.categoryData = []
            },
            close() {
                this.searchReset(0);
                this.visible = false;
            },
            handleSubmit() {
                let that = this;
                that.$emit('ok', {positions: that['positionsData'], users: that['usersData'], val: this.userInfo});
                that.searchReset(0)
                that.close();
            },
            /**
             * 手动全选/取消全选分类
             * @param selected
             * @param selectedRows
             * @param changeRows
             */
            onSelectAll(selected, selectedRows, changeRows) {
              if(this.activeKey == 'user'){
                this[this.activeKey + 'SelectedRowKeys'] =selectedRows.map(row => row['id']);
                this[this.activeKey + 'SelectionRows'] = selectedRows
              }else{
                this[this.activeKey + 'SelectedRowKeys'] = selectedRows.map(row => row[this.activeKey + 'Code']);
                this[this.activeKey + 'SelectionRows'] = selectedRows
              }
                if (selected) {
                  let data_ = this[this.activeKey + 'sData']
                    //todo 选中
                    changeRows.map(row => {
                      let n = 0
                      if (data_!=null && data_!=undefined){
                        for (let i = 0; i < data_.length; i++) {
                          if (data_[i].mainPosition == 0){
                            n = 1
                            break
                          }
                        }
                        if (n == 1){
                          row.mainPosition  = 1
                        }
                      }
                        this[this.activeKey + 'sData'].push(row)
                    })
                } else {
                    //todo 取消选中
                    changeRows.map(row => {
                        this[this.activeKey + 'sData'].removeByCode(row, this.activeKey + 'Code')
                    })
                }
            },

            /**
             * 手动勾选/取消分类
             * @param record
             * @param selected
             * @param selectedRows
             * @param nativeEvent
             */
            onSelect(record, selected, selectedRows, nativeEvent) {
              if(this.activeKey == 'user'){
                this[this.activeKey + 'SelectedRowKeys'] =selectedRows.map(row => row['id']);
                this[this.activeKey + 'SelectionRows'] = selectedRows.slice(0)
              }else{
                this[this.activeKey + 'SelectedRowKeys'] = selectedRows.map(row => row[this.activeKey + 'Code']);
                this[this.activeKey + 'SelectionRows'] = selectedRows.slice(0)
              }
              if (selected) {
                //todo 选中
                let data_ = this[this.activeKey + 'sData']
                let n = 0
                this[this.activeKey + 'sData'].push({...record})
              } else {
                //todo 取消选中
                if(this.activeKey == 'user'){ this[this.activeKey + 'sData'].removeByCode(record,  'id')}else{
                  this[this.activeKey + 'sData'].removeByCode(record, this.activeKey + 'Code')
                }

              }
            },
            onSearch() {
                this.loadData(1);
            },

            /**
             * 覆盖mixin的loadData方法
             * @param arg
             * @returns {Promise<void>}
             */
            async loadData(arg) {
                if (arg === 1) {
                    this.ipagination.current = 1;
                }
                let url
              if (this.activeKey === 'user') {
                url = '/cnUserController/getPageList'
              }
                this.loading = true
                let params = this.getQueryParams()//查询条件
                await postAction(url, {...params}).then((res) => {
                    if (res.success) {
                        this[this.activeKey + 's'] =  res.result.records
                        this.ipagination.total = res.result.total
                    }
                }).finally(() => {
                    this.loading = false
                })
            },
            /**
             * 获取已选中数据
             */
            getSelectdData() {
                const userUrl =  '/cnOrgController/getUserOrg'
                return Promise.all([
                  getAction(userUrl, {orgCode: this.userInfo.orgCode})
                ]).then(([user]) => {
                    if (user.result && user.result.length) {
                        this['userSelectedRowKeys'] = user.result.map(row => row.id);
                        this['userSelectionRows'] = user.result
                        this['usersData'] = user.result
                    }
                })
            },
            /**
             * 获取分类树
             * @returns {*}
             */
            queryDepartTree() {
                this.typeLoading = true
                return queryDepartTreeList().then((res) => {
                    if (res.success) {
                        this.treeData = this.handleStruct(res.result);
                        // 默认展开父节点
                        this.expandedKeys = this.treeData.map(item => item.code)
                    }

                    this.typeLoading = false
                }).catch(e => {
                    this.$message.warning(res.message);
                    this.typeLoading = false
                })
            },
            /**
             * 重构树结构数据
             * @param tree
             * @returns {*}
             */
            handleStruct(tree) {
                return tree.map(t => {
                    const json = Object.assign({}, t, {
                        code: t.orgCode,
                        name: t.orgName,
                        type: t.orgType
                    })
                    if (json.children) {
                        json.children = this.handleStruct(json.children)
                    }
                    return json
                })
            },
            modalFormOk() {
                this.loadData();
            }
        },
    }
</script>

<style scoped>
    .ant-table-tbody .ant-table-row td {
        padding-top: 10px;
        padding-bottom: 10px;
    }

    #components-layout-demo-custom-trigger .trigger {
        font-size: 18px;
        line-height: 64px;
        padding: 0 24px;
        cursor: pointer;
        transition: color .3s;
    }
</style>
